import { QueryKey, useMutation, useQuery } from "react-query";
import { useHttp } from "./http";
import { cleanObject } from "./index";
import { Task } from "../type/task";
import { useDeleteConfig } from "./use-optimistic-options";

export const useTask = (param?: Partial<Task>) => {
    const client = useHttp();
    return useQuery<Task[]>(['tasks', param],
        () => client('tasks', {
            data: cleanObject(param || {})
        })
    )
};

export const useTaskDetail = (id?: number) => {
    const client = useHttp();
    return useQuery(
        ['tasks', { id }],
        () => client(`tasks/${id}`),
        {
            enabled: Boolean(id)
        }
    )
}

export const useDeleteTask = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        ({ id }: { id: number }) =>
            client(`tasks/${id}`, {
                method: "DELETE",
            }),
        useDeleteConfig(queryKey)
    )
}

export const useAddTask = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        (params: Partial<Task>) =>
            client(`tasks`, {
                method: "POST",
                data: params
            }),
        useDeleteConfig(queryKey)
    )
}

export const useEditTask = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        (params: Partial<Task>) =>
            client(`tasks/${params.id}`, {
                method: "PATCH",
                data: params
            }),
        useDeleteConfig(queryKey)
    )
}
